package com.example.book_libapp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.database.library.BookFunctions;
import com.example.database.library.DatabaseHandler;

public class BookDetails extends Activity {

	private static final String TAG_ID = "id";
	private static final String TAG_BOOK = "book";
	private static final String TAG_STAT = "stat";
	private static final String TAG_TITLE = "title";
	private static final String TAG_INFO = "introduction";
	private static final String TAG_COVER = "cover";
	private static final String TAG_PAGE = "page_count";
	private static final String TAG_AUTHOR = "author";
	private static final String TAG_VCOUNT = "rates_count";
	private static final String TAG_PUBYEAR = "published_year";
	private static final String TAG_RATING = "rating";
	private static final String TAG_PRESS = "in_press";

	private static final String TAG_META = "meta";
	static final String TAG_CATE = "category";
	static final String TAG_CRATE = "rate";
	static final String TAG_CREVIEW = "review";
	static final String TAG_CREVIEWS = "reviews";
	static final String TAG_CREBY = "reviewed_by";
	static final String TAG_CREAT = "reviewed_at";

	static final String TAG_OWNER = "owner";
	static final String TAG_CPAGE = "page";
	static final String TAG_CPAGES = "pages";

	private Button btndownload;
	private Button btnbookrating;
	public ImageLoader imageLoader;
	ArrayList<HashMap<String, String>> contactList;
	int pagecount;
	QuickAction mQuickAction;
	boolean endpage = false;
	BookCommentAdapter adapter;
	HashMap<String, String> map;
	String book_id;
	ProgressBar pb;
	String comment = "";
	float rating = 0;
	Dialog dialog;
	String token;
	int downloadedSize = 0;
	int totalSize = 0;
	TextView cur_val;
	ListView Commentlist;
	String dwnload_file_path = "http://98.131.47.233/transfer/Books/Android%20Development%20Books/Multimobile.Development.pdf";

	public void onSearch(View v) {
		onSearchRequested();
	}

	public void onHome(View v) {
		return2Home(this);
	}

	public void return2Home(Context context) {
		final Intent intent = new Intent(context, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		context.startActivity(intent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_information);

		// Add action item
		ActionItem editAction = new ActionItem();

		editAction.setTitle("Edit");
		editAction.setIcon(getResources().getDrawable(R.drawable.icon_save));

		// Accept action item
		ActionItem delAction = new ActionItem();

		delAction.setTitle("Delete");
		delAction.setIcon(getResources().getDrawable(R.drawable.icon_delete));

		mQuickAction = new QuickAction(this);

		mQuickAction.addActionItem(editAction);
		mQuickAction.addActionItem(delAction);

		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(int pos) {

						if (pos == 0) { // edit item selected
							showRatingDialog(comment, rating, false);
							
						} else if (pos == 1) { // delete item selected
							BookDeleteReview();
						} 
					}
				});

		TextView tvTitle = (TextView) findViewById(R.id.detailbooktitle);
		TextView tvInfo = (TextView) findViewById(R.id.detailbookinfo);
		TextView tvAuthor = (TextView) findViewById(R.id.detailbookauthor);
		TextView tvRatescount = (TextView) findViewById(R.id.detailbookviewcount);
		TextView tvPublishedyear = (TextView) findViewById(R.id.detailbookpublishedyear);
		TextView tvPagecount = (TextView) findViewById(R.id.detailbookpagecount);
		RatingBar RatingBarBook = (RatingBar) findViewById(R.id.ratingbar_Small);

		ImageView cover = (ImageView) findViewById(R.id.detailsbookcover);
		imageLoader = new ImageLoader(this.getApplicationContext());
		btnbookrating = (Button) findViewById(R.id.BtnRatinggive);
		btndownload = (Button) findViewById(R.id.Btnbookdownload);
		book_id = "1";
		Commentlist = (ListView) findViewById(R.id.CommentlistView);

		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		token = db.getUserToken();
		Commentlist.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				String owner = ((TextView) v.findViewById(R.id.owner))
						.getText().toString();
				Log.i("OWNER", "" + owner);
				if (owner == "true") {
					bookcommentowner(v);
				} 
			
			}
		});
		// get intent data
		Intent i = getIntent();
		book_id = i.getStringExtra(TAG_ID);

		BookFunctions BookFunction = new BookFunctions();
		JSONObject json;
		JSONObject jsonbook;
		pagecount = 0;
		json = BookFunction.BookInfo(book_id);

		try {
			if (json.getString(TAG_STAT).toString().equals("ok")) {
				jsonbook = json.getJSONObject(TAG_BOOK);

				tvTitle.setText(""
						+ getString(R.string.bookdetails_label_title) + " "
						+ jsonbook.getString(TAG_TITLE));
				tvInfo.setText("" + getString(R.string.bookdetails_label_info)
						+ " " + jsonbook.getString(TAG_INFO));
				tvAuthor.setText(""
						+ getString(R.string.bookdetails_label_author) + " "
						+ jsonbook.getString(TAG_AUTHOR));
				tvRatescount.setText(""
						+ getString(R.string.bookdetails_label_viewcount) + " "
						+ jsonbook.getString(TAG_VCOUNT));
				tvPublishedyear.setText(""
						+ getString(R.string.bookdetails_label_pubyear) + " "
						+ jsonbook.getString(TAG_PUBYEAR));
				tvPagecount.setText(""
						+ getString(R.string.bookdetails_label_pages) + " "
						+ jsonbook.getString(TAG_PAGE));
				RatingBarBook.setRating(Float.parseFloat(jsonbook.getString(
						TAG_RATING).toString()));
				imageLoader.DisplayImage(jsonbook.getString(TAG_COVER)
						.toString(), cover);
				Log.e("Rating bar", ""
						+ jsonbook.getString(TAG_RATING).toString());

			} else {

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		contactList = new ArrayList<HashMap<String, String>>();
		btnbookrating.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showRatingDialog("", 0, true);

			}
		});

		// Commentlist.setOnScrollListener(new OnScrollListener(){
		//
		// //useless here, skip!
		// @Override
		// public void onScrollStateChanged(AbsListView view, int scrollState)
		// {}
		//
		// //dumdumdum
		// @Override
		// public void onScroll(AbsListView view, int firstVisibleItem,
		// int visibleItemCount, int totalItemCount) {
		//
		//
		// //what is the bottom iten that is visible
		// int lastInScreen = firstVisibleItem + visibleItemCount;
		//
		// //is the bottom item visible & not loading more already ? Load more !
		// if((lastInScreen == totalItemCount) && endpage == false){
		// Log.v("Scroll Event", "Scroll Event Scroll Event Scroll Event");
		// new loadMoreListView().execute();
		// }
		// }
		// });

		// btnbookcomment.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		btndownload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(),
				// "BOOK", Toast.LENGTH_LONG).show();

				showProgress(dwnload_file_path);

				new Thread(new Runnable() {
					public void run() {
						downloadFile();
					}
				}).start();

				// new DownloadFileFromURL().execute(file_url);
			}
		});

		// btnVote.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// showRatingDialog();
		// }
		// });

		new loadMoreListView().execute();

	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.menu_bookmark:
			// Single menu item is selected do something
			// Ex: launching new activity/screen or show alert message
			Toast.makeText(BookDetails.this, "Bookmark is Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_save:
			Toast.makeText(BookDetails.this, "Save is Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_search:
			Intent i = new Intent(this, Booksearch.class);
			startActivity(i);
			return true;
		case R.id.menu_share:
			Intent i1 = new Intent(this, BookHistory.class);
			startActivity(i1);
			return true;
		case R.id.menu_delete:
			Toast.makeText(BookDetails.this, "Delete is Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_preferences:
			Toast.makeText(BookDetails.this, "Preferences is Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void showRatingDialog(String c, float r, boolean stat) {

		DialogBookRating dialograting = new DialogBookRating(this);
		dialograting.show();
		if (stat != true) {
			dialograting.setUpdate(c, r);
		} 
		
	}

	public void setInsertReview(float s, String r) {

		BookFunctions BookFunction = new BookFunctions();
		
		JSONObject json;
		
		json = BookFunction.BookNewReview(token, book_id, r, Float.toString(s));
		Log.e("JSON", ""
				+ json.toString());
		try {
			if (json.getString(TAG_STAT).toString().equals("ok")) {
//


			} else {
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void setUpdateReview(float s, String review) {
		BookFunctions BookFunction = new BookFunctions();
		
		JSONObject json;
		
		json = BookFunction.BookEditReview(token, book_id, review, Float.toString(s));
		Log.e("JSON", ""
				+ json.toString());
		try {
			if (json.getString(TAG_STAT).toString().equals("ok")) {
//
//				Log.e("Rating bar", ""
//						+ jsonbook.getString(TAG_RATING).toString());
				Toast.makeText(BookDetails.this, "update", Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(BookDetails.this, "no update", Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
	
	void BookDeleteReview() {
		BookFunctions BookFunction = new BookFunctions();
		JSONObject json;
		json = BookFunction.BookDeleteReview(token, book_id);
		Log.e("JSON", ""
				+ json.toString());
		try {
			if (json.getString(TAG_STAT).toString().equals("ok")) {
			//	jsonbook = json.getJSONObject(TAG_BOOK);
//
//				Log.e("Rating bar", ""
//						+ jsonbook.getString(TAG_RATING).toString());

			} else {
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	void downloadFile() {

		try {
			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			File file = new File(SDCardRoot, "downloaded_file.png");

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are downloading
			totalSize = urlConnection.getContentLength();

			runOnUiThread(new Runnable() {
				public void run() {
					pb.setMax(totalSize);
				}
			});

			// create a buffer...
			byte[] buffer = new byte[1024];
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				// update the progressbar //
				runOnUiThread(new Runnable() {
					public void run() {
						pb.setProgress(downloadedSize);
						float per = ((float) downloadedSize / totalSize) * 100;
						cur_val.setText("Downloaded " + downloadedSize
								+ "KB / " + totalSize + "KB (" + (int) per
								+ "%)");
					}
				});
			}
			// close the output stream when complete //
			fileOutput.close();
			runOnUiThread(new Runnable() {
				public void run() {
					dialog.dismiss();
				}
			});

		} catch (final MalformedURLException e) {
			showError("Error : MalformedURLException " + e);
			e.printStackTrace();
		} catch (final IOException e) {
			showError("Error : IOException " + e);
			e.printStackTrace();
		} catch (final Exception e) {
			showError("Error : Please check your internet connection " + e);
		}
	}

	void showError(final String err) {
		runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(BookDetails.this, err, Toast.LENGTH_LONG).show();
			}
		});
	}

	
	void showProgress(String file_path) {
		dialog = new Dialog(BookDetails.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.myprogressdialog);
		dialog.setTitle(R.string.bookdetails_download_title);

		TextView text = (TextView) dialog.findViewById(R.id.tv1);
		text.setText("" + getString(R.string.bookdetails_label_download)
				+ file_path);
		cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
		cur_val.setText(R.string.bookdetails_download_starting);
		dialog.show();

		pb = (ProgressBar) dialog.findViewById(R.id.progress_bar);
		pb.setProgress(0);
		pb.setProgressDrawable(getResources().getDrawable(
				R.drawable.green_progress));
	}

	public void bookcommentowner(View v) {
		 mQuickAction.show(v);
		 mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		 comment = "" + ((TextView)
		 v.findViewById(R.id.comment)).getText().toString();
		 rating = ((RatingBar)
		 v.findViewById(R.id.ratingbar_Small1)).getRating();
		 
		 Log.i("MSSSSSSSSS", "" + comment.toString() + " " + rating);
	}
	
	private class loadMoreListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
					JSONObject json;

					JSONObject jsoncomment;

					JSONArray contacts = null;
					pagecount++;
					BookFunctions BookFunction = new BookFunctions();
					json = BookFunction.BookReview(pagecount, book_id, token);
					try {

						Log.e("JSON",
								"aldaa --------------------------------------------------"
										+ json.getString(TAG_STAT).toString()
										+ "page number:" + pagecount
										+ " bookid:" + book_id + "");

						if (json.getString(TAG_STAT).toString().equals("ok")) {

							jsoncomment = json.getJSONObject(TAG_CREVIEWS);

							if (Integer.parseInt(jsoncomment
									.getString(TAG_CPAGE)) == Integer
									.parseInt(jsoncomment.getString(TAG_CPAGES))) {
								endpage = true;
								Log.e("loadingMore",
										"loadingMore doInBackground --------------------------------------------------");
							}

							// DatabaseHandler db = new
							// DatabaseHandler(getApplicationContext());
							// db.resetBookListInfoTables();
							// db.addBooklistinfo(jsonbook.getString(TAG_PAGE),
							// jsonbook.getString(TAG_PERPAGE),jsonbook.getString(TAG_TOTAL),jsonbook.getString(TAG_PAGES));
							// db.addBooklistinfo("asdf","asdfasdf","asfasdf","asfasdf");
							contacts = jsoncomment.getJSONArray(TAG_CREVIEW);
							Log.e("cOMMENT1",
									"aldaa --------------------------------------------------");
							for (int i = 0; i < contacts.length(); i++) {
								JSONObject c = contacts.getJSONObject(i);
								String rate = c.getString(TAG_CRATE);
								String review = c.getString(TAG_CREVIEW);
								String reviewed_by = c.getString(TAG_CREBY);
								String reviewed_at = c.getString(TAG_CREAT);
								String owner = c.getString(TAG_OWNER);

								// Log.e("Book", " " + id + " " + " " + title
								// +" " + brief +" ");
								// // creating new HashMap
								HashMap<String, String> map = new HashMap<String, String>();

								// adding each child node to HashMap key =>
								// value
								map.put(TAG_CRATE, rate);
								map.put(TAG_CREVIEW, review);
								map.put(TAG_CREBY, reviewed_by);
								map.put(TAG_CREAT, reviewed_at);
								map.put(TAG_OWNER, owner);

								// adding HashList to ArrayList
								contactList.add(map);
							}
							Log.e("cOMMENT2",
									"aldaa --------------------------------------------------");
						} else {
							// Toast msg =
							// Toast.makeText(getApplicationContext(),
							// "Сэтгэгдэл байхгүй.", Toast.LENGTH_LONG);
							// msg.show();
							endpage = true;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

					// int currentPosition =
					// Commentlist.getFirstVisiblePosition();
					Log.e("cOMMENT3",
							"aldaa --------------------------------------------------");
					// Getting adapter by passing xml data ArrayList
					adapter = new BookCommentAdapter(BookDetails.this,
							contactList);
					Commentlist.setAdapter(adapter);
					Log.e("cOMMENT4",
							"aldaa --------------------------------------------------");
					// Commentlist.setSelectionFromTop(currentPosition + 1, 0);
				}
			});

			return (null);
		}

		protected void onPostExecute(Void unused) {

		}
	}
}
